package org.bear.bundle.framework.controller;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;

import org.apache.activemq.BlobMessage;
import org.apache.activemq.command.ActiveMQBlobMessage;
import org.bear.bundle.framework.JMSConsumer;
import org.bear.bundle.framework.JMSProducer;
import org.bear.bundle.framework.controller.MessageType.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageController {

	private static final Logger log = LoggerFactory
			.getLogger(MessageController.class);

	private static final String StatusQueue = "STATUE.CENTER";

	// MQ连接url
	public static String brokerUrl;
	// MQ用户名
	public static String username;
	// MQ密码
	public static String password;
	// IP地址
	public static String ip;
	// 插件名称
	private String osgiName;
	// 客户端状态回送频率
	public static String pattern;

//	private String proxyIp;

	public void initProperties() {
	}

	
	public void sendResultToHistory(boolean isSuccess, String historyID) {
		if (historyID == null || historyID.equals("")) {
			return;
		}

		String isSuccessResult = isSuccess == true ? "1" : "0";

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tableName", "snc_mq_jobhistory");
		map.put("filedID", historyID);
		map.put("idName", "id");
		map.put("fieldName", "status");
		map.put("result", isSuccessResult);
		JMSProducer jmsProducer = new JMSProducer(brokerUrl, username, password);
		try {
			jmsProducer.send("RESULT.CENTER", map, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取MessageProducer或essageConsumer
	 * 
	 * @return Object
	 */
	public Object getJMSObject(boolean isProducer) {
		if (isProducer) {
			return new JMSProducer(brokerUrl, username, password);
		} else {
			return new JMSConsumer(brokerUrl, username, password, ip);
		}
	}

	/**
	 * JMS发送消息
	 * 
	 * @param queue
	 * @param map
	 * @param object
	 */
	public static void send(String queue, Map<String, Object> map, Object object) {
		JMSProducer producer = new JMSProducer(brokerUrl, username, password);
		try {
			producer.send(queue, map, object);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * JMS接收消息1
	 * 
	 * @param messageListener
	 * @param queue
	 * @return JMSConsumer
	 */
	public static JMSConsumer receive(MessageListener messageListener,
			String queue) {
		JMSConsumer consumer = new JMSConsumer(brokerUrl, username, password,
				ip);
		consumer.setMessageListener(messageListener, queue);
		return consumer;
	}

	/**
	 * JMS接收消息2
	 * 
	 * @param queue
	 * @param timeout
	 * @return Message
	 */
	public static Message receive(String queue, Long timeout) {
		Message message = null;

		JMSConsumer consumer = new JMSConsumer(brokerUrl, username, password,
				ip);
		try {

			MessageConsumer messageConsumer = consumer
					.getMessageConsumer(queue);

			Worker worker = new Worker(messageConsumer);
			worker.start();

			try {

				worker.join(timeout);

				message = worker.getResult();

			} catch (Exception ex) {
				worker.interrupt();
				Thread.currentThread().interrupt();

				ex.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			consumer.shutdown();
		}

		return message;
	}

	private static class Worker extends Thread {
		private final MessageConsumer messageConsumer;
		private Message result;

		private Worker(MessageConsumer messageConsumer) {
			this.messageConsumer = messageConsumer;
		}

		public void run() {
			try {
				setResult(messageConsumer.receive());
			} catch (Exception ex) {
				return;
			}
		}

		public Message getResult() {
			return result;
		}

		public void setResult(Message result) {
			this.result = result;
		}
	}

	/**
	 * 输出日志
	 * 
	 * @param taskID
	 * @param tips
	 * @param type
	 * @param message
	 */
	public void outinfo(String taskID, String tips, Type type, String message) {
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("[").append(Type.getNameByIndex(type.getIndex()))
				.append("]:");
		sBuilder.append("[").append(this.getOsgiName()).append("]:");
		sBuilder.append("[").append(taskID).append("]:");
		sBuilder.append("[").append(tips).append("]:");
		sBuilder.append(message);

		log.error(sBuilder.toString());
	}

	/**
	 * 送回任务状态(后续服务端统一处理)
	 * 
	 * @param taskID
	 * @param isSuccess
	 *            (0失败1成功)
	 * @param precent
	 * @param currentStatus
	 */
	public void sendCurrentStatus(String taskID, int isSuccess, String precent,
			int currentStatus) {
		JMSProducer statusProducer = (JMSProducer) getJMSObject(true);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("taskID", taskID);
		map.put("isSuccess", isSuccess);
		map.put("precent", precent);
		map.put("currentStatus", currentStatus);

		statusProducer.send(StatusQueue, map, null);
	}

	/**
	 * 清楚ActiveMQ缓存文件
	 * 
	 * @param blobMessage
	 */
	public void clearActiveMQFile(BlobMessage blobMessage) {
		try {
			((ActiveMQBlobMessage) blobMessage).deleteFile();
			outinfo("MQ_DELETE_FILE", "清除ActiveMQ缓存成功", Type.INFO, "Success");
		} catch (Exception e) {
			outinfo("MQ_DELETE_FILE", "清除ActiveMQ缓存异常", Type.EXCEPTION,
					"Failure:" + e.getMessage());
		}
	}

	public String getOsgiName() {
		return osgiName;
	}

	public void setOsgiName(String osgiName) {
		this.osgiName = osgiName;
	}

}
